<script lang="ts" setup>
import { Notification } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import type { TableRowSelection } from '@arco-design/web-vue'
import TableToolBar from '@/components/TableToolBar/index.vue'
import MyTransition from '@/components/MyTransition/index.vue'
import MyApp from '@/components/MyApp/index.vue'
import { TitleMap, BasePagination } from '@/config/constants'
import { set } from '@vueuse/core'
import request from '@/utils/request'
import { debounce } from 'lodash'
import Edit from './edit.vue'

interface EditProps {
  navId: number
}

const props = withDefaults(defineProps<EditProps>(), {
  navId: 0,
})

const { page, limit } = BasePagination
const data = reactive({
  modelForm: {
    navId: 1,
  },
  // 查询对象
  queryParams: {
    title: '',
    page,
    limit,
    appId: 1,
    navId: 1,
  },
  // 列表数据
  tableData: [],
})
// const { paneList } = toRefs(props)
const showSearch = ref(true)
const tableLoading = ref(false)
const editVisible = ref(false)
const delDisabled = ref(true)
const dialogStatus = ref('create')
const selectedKeys = ref<any>([])
const expandedKeys = ref<any>([])
const formQueryRef = ref<FormInstance>()
const rowSelection: TableRowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
}

const setEditVisible = () => {
  set(editVisible, false)
}
const onSearch = debounce(() => {
  getList()
}, 500)

const onReset = debounce(() => {
  formQueryRef.value?.resetFields()
  getList()
}, 500)

// 新增
const onAdd = () => {
  set(editVisible, true)
  set(dialogStatus, 'create')
}

// 获取列表
const getList = () => {
  set(tableLoading, true)
  request({
    url: '/category',
    params: data.queryParams,
  }).then((res) => {
    if (Array.isArray(res?.rows) && res?.rows) {
      data.tableData = res.rows
    }

    setTimeout(() => {
      set(tableLoading, false)
    }, 80)
  })
}

getList()

// 处理编辑
const handleEdit = (row: any) => {
  set(editVisible, true)
  set(dialogStatus, 'update')
  row.ord += ''

  Object.assign(data.modelForm, row)
}

// 批量删除
const onRemove = () => {
  if (!selectedKeys.value.length) {
    Notification.error('至少选择一个')
    return
  }

  onDelete(selectedKeys.value.join(','))
}

// 处理删除
const handleDelete = (data: any) => {
  onDelete(data?.id)
}

// 删除
const onDelete = (id: string) => {
  request({
    method: 'delete',
    url: `/category/${id}`,
  }).then((res) => {
    set(dialogStatus, 'delete')
    res && handleSuccess()
  })
}

// 新增数据
const createData = (data: any) => {
  request({
    method: 'post',
    url: '/category',
    data,
  }).then((res) => {
    res && handleSuccess()
  })
}

// 修改数据
const updateData = (data: any) => {
  request({
    method: 'patch',
    url: `/category/${data.id}`,
    data,
  }).then((res) => {
    res && handleSuccess()
  })
}

// 处理成功
const handleSuccess = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  getList()
  Notification.info({
    content: `${TitleMap[dialogStatus.value as keyof typeof TitleMap] || '操作'}成功`,
    duration: 3000,
  })
}

// 监听批量删除按钮
watch(
  () => selectedKeys.value.length,
  (value) => {
    delDisabled.value = !value
  },
  { immediate: true }
)

// 监听tab切换
watch(
  () => props.navId,
  (v: any) => {
    data.queryParams.navId = v
    data.modelForm.navId = v
    data.queryParams.page = 1
    getList()
  },
  { immediate: true }
)

// 监听应用
watch(
  () => data.queryParams.appId,
  (v: any) => {
    data.queryParams.appId = v
    data.queryParams.page = 1
    getList()
  },
  { immediate: true }
)
</script>
<template>
  <div class="app-job-category">
    <my-transition>
      <div class="app-card-header" v-show="showSearch">
        <a-form ref="formQueryRef" :model="data.queryParams" layout="inline" @submit="onSearch">
          <a-form-item label="应用">
            <MyApp v-model="data.queryParams.appId" />
          </a-form-item>
          <a-form-item field="title" label="名称">
            <a-input v-model.trim="data.queryParams.title" :style="{ width: '320px' }" allow-clear placeholder="请输入名称" @keyup.enter="onSearch" />
          </a-form-item>
          <a-form-item>
            <a-space :size="10">
              <a-button type="primary" html-type="submit">
                <template #icon>
                  <icon-search />
                </template>
                <template #default>查询</template>
              </a-button>
              <a-button @click="onReset">
                <template #icon>
                  <icon-refresh />
                </template>
                <template #default>重置</template>
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </my-transition>
    <div class="app-card-body">
      <div class="app-table-action">
        <div class="app-table-btn">
          <a-space :size="10">
            <a-button type="primary" @click="onAdd">
              <template #icon>
                <icon-plus />
              </template>
              <template #default>新增</template>
            </a-button>
            <a-button type="outline" status="danger" :disabled="delDisabled" @click="onRemove">
              <template #icon>
                <icon-delete />
              </template>
              <template #default>删除</template>
            </a-button>
          </a-space>
        </div>
        <div class="app-table-action-right">
          <table-tool-bar v-model:show-search.sync="showSearch" @query-table="getList" />
        </div>
      </div>
      <!-- /table-action -->
      <div class="app-pane-table">
        <a-table :data="data.tableData" stripe row-key="id" :loading="tableLoading" :row-selection="rowSelection" v-model:selectedKeys="selectedKeys" v-model:expandedKeys="expandedKeys">
          <template #columns>
            <a-table-column title="id" data-index="id" />
            <a-table-column title="序号" data-index="order" :width="180" />
            <a-table-column title="名称" data-index="title" :width="180" />
            <a-table-column title="描述" data-index="description" />
            <a-table-column title="创建时间" data-index="createTime" />
            <a-table-column title="操作" :width="80">
              <template #cell="{ record }">
                <a-space>
                  <a-button type="text" @click="handleEdit(record)">
                    <template #icon>
                      <icon-edit />
                    </template>
                    <template #default>修改</template>
                  </a-button>
                  <a-button type="text" status="danger" @click="handleDelete(record)">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <!-- /table-container -->
      <Edit :model-form="data.modelForm" :nav-id="data.queryParams.navId" :category-options="data.tableData" v-model:edit-visible="editVisible" :set-edit-visible="setEditVisible" :create-data="createData" :update-data="updateData" :dialog-status="dialogStatus" />
    </div>
  </div>
</template>
<style lang="scss"></style>
